package com.webmeeting.chat.wordchat.dao.daos;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.myframework.utils.dbutil.DatabaseUtil;
import com.myframework.utils.exceptions.WMDaoException;
import com.myframework.utils.logutil.WMLogger;
import com.myframework.utils.stringutil.StringUtil;
import com.webmeeting.chat.wordchat.dao.daos.interfaces.UserDAO;
import com.webmeeting.chat.wordchat.dao.entities.User;

public class UserDAOMySQLImpl implements UserDAO {

	@Override
	public long createUser(String username, String password, String nickname) throws WMDaoException {
		if (StringUtil.isEmpty(username) || StringUtil.isEmpty(password) || StringUtil.isEmpty(nickname)) {
			throw new WMDaoException("Username and password can not be empty!");
		}

		long result = 0;
		StringBuilder sql = new StringBuilder("INSERT INTO USER (USERNAME, PASSWORD, NICKNAME, CREATE_DATE) VALUES (?, ?, ?, ?)");
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = DatabaseUtil.getConnection();

		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, username);
			ps.setString(2, password);
			ps.setString(2, nickname);
			ps.setTimestamp(3, new java.sql.Timestamp(System.currentTimeMillis()));

			int numRowsInserted = ps.executeUpdate();
			if (numRowsInserted <= 0) {
				throw new WMDaoException("No user is inserted into database.");
			}

			ps.close();
			ps = DatabaseUtil.getConnection().prepareStatement(DatabaseUtil.buildIdentitySelect("USER"));
			rs = ps.executeQuery();

			if (rs.next()) {
				result = rs.getLong(1);
			} else {
				throw new WMDaoException("Can not find the last inserted id.");
			}
			WMLogger.debug("A new user is inserted into database with username: " + username);
		} catch (WMDaoException e) {
			WMLogger.error("", e);
		} catch (SQLException e) {
			WMLogger.error("", e);
		} finally {
			if (null != rs) {
				try {
					rs.close();
				} catch (SQLException e) {
					WMLogger.error("", e);
				}
			}

			if (null != ps) {
				try {
					ps.close();
				} catch (SQLException e) {
					WMLogger.error("", e);
				}
			}
		}

		return result;
	}

	@Override
	public void deleteUser(String username) throws WMDaoException {
		if (StringUtil.isEmpty(username)) {
			throw new WMDaoException("Username can not be empty!");
		}

		StringBuffer sql = new StringBuffer("DELETE FROM USER WHERE USERNAME = ?");
		PreparedStatement ps = null;
		Connection conn = DatabaseUtil.getConnection();

		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, username);

			int numRowsDeleted = ps.executeUpdate();
			if (numRowsDeleted < 0) {
				throw new WMDaoException("No user is deleted from database.");
			}
			WMLogger.debug("Delete a user from database with username: " + username);
		} catch (WMDaoException e) {
			WMLogger.error("", e);
		} catch (SQLException e) {
			WMLogger.error("", e);
		} finally {
			if (null != ps) {
				try {
					ps.close();
				} catch (SQLException e) {
					WMLogger.error("", e);
				}
			}
		}

		return;
	}

	@Override
	public User findUserByName(String username) throws WMDaoException {
		if (StringUtil.isEmpty(username)) {
			throw new WMDaoException("Username can not be empty!");
		}

		User result = null;
		StringBuilder sql = new StringBuilder("SELECT * FROM USER WHERE USERNAME = ?");
		PreparedStatement ps = null;
		ResultSet rs = null;
		Connection conn = DatabaseUtil.getConnection();

		try {
			ps = conn.prepareStatement(sql.toString());
			ps.setString(1, username);

			rs = ps.executeQuery();

			if (rs.next()) {
				result = new User(DatabaseUtil.buildColumnMap(rs));
			} else {
				WMLogger.debug("Can not find a user with username: " + username);
			}
			if (null != result) {
				WMLogger.debug("Retrieve a user with username: " + username);
			} else {
				WMLogger.debug("Can not find a user with username: " + username);
			}
		} catch (SQLException e) {
			WMLogger.error("", e);
		} finally {
			if (null != rs) {
				try {
					rs.close();
				} catch (SQLException e) {
					WMLogger.error("", e);
				}
			}

			if (null != ps) {
				try {
					ps.close();
				} catch (SQLException e) {
					WMLogger.error("", e);
				}
			}
		}

		return result;
	}

}
